Move = class()

function Move:init(world)
    self.world = world
    self.touchMap = {}
    self.open = true
end

function Move:draw()
    if self.open == true then
        pushStyle()
        smooth()
        strokeWidth(5)
        stroke(128,0,128, 255)
        
        local gain = 20
        local damp = 2
        for k,v in pairs(self.touchMap) do
            local worldAnchor = v.body:getWorldPoint(v.anchor)
            local touchPoint = v.tp
            local diff = touchPoint - worldAnchor
            local vel = v.body:getLinearVelocityFromWorldPoint(worldAnchor)
            v.body:applyForce( (1/1) * diff * gain - vel * damp, worldAnchor)
            
            line(touchPoint.x, touchPoint.y, worldAnchor.x, worldAnchor.y)
        end
        popStyle()
    end
end

function Move:touched(touch)
    if self.open == true then
        local touchPoint = vec2(touch.x, touch.y)
        if touch.state == BEGAN then
            for i,body in ipairs(self.world.objects) do
                if body.type == DYNAMIC and body:testPoint(touchPoint) then
                    self.touchMap[touch.id] = {tp = touchPoint, body = body, anchor = body:getLocalPoint(touchPoint)}
                    return true
                end
            end
        elseif touch.state == MOVING and self.touchMap[touch.id] then
            self.touchMap[touch.id].tp = touchPoint
            return true
        elseif touch.state == ENDED and self.touchMap[touch.id] then
            self.touchMap[touch.id] = nil
            return true;
        end
        return false
    end
end

function Move:changeOpen()
    self.open = not self.open
end
